package com.feishi.core.util.encrypt.ssl;


import javax.net.ssl.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.security.*;
import java.security.cert.CertificateException;

/**
 * Created by caixq on 4/28 028.
 */
public class SSLUtil {
    private static final String     PROTOCOL    = "TLS";
    public static SSLContext createSSLContext(InputStream keystoreStream, String keyStorePassword, InputStream keystoreTrustStream) throws NoSuchAlgorithmException, UnrecoverableKeyException, KeyStoreException, IOException, CertificateException, KeyManagementException {
        KeyManager[] kms=null;


        if(keystoreStream!=null && keyStorePassword!=null){
            KeyStore ks = KeyStore.getInstance("JKS");
            ks.load(keystoreStream, keyStorePassword.toCharArray());
            // Set up key manager factory to use our key store
            KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            kmf.init(ks, keyStorePassword.toCharArray());
            kms = kmf.getKeyManagers();
        }


        // truststore

        TrustManager[] tms = null;
        TrustManagerFactory tmf=null;
        if(keystoreTrustStream!=null){
            KeyStore ts = KeyStore.getInstance("JKS");
            ts.load(keystoreTrustStream, keyStorePassword.toCharArray());
            // set up trust manager factory to use our trust store
            tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            tmf.init(ts);
            tms= tmf.getTrustManagers();
        }

        // Initialize the SSLContext to work with our key managers.
        SSLContext serverContext = SSLContext.getInstance(PROTOCOL);


        serverContext.init(kms, tms, null);


        return serverContext;
    }
    public static SSLContext createSSLContext(InputStream keystoreStream, String keyStorePassword) throws CertificateException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException, IOException {
        return createSSLContext(keystoreStream,keyStorePassword,null);
    }
    public static SSLContext createSSLContext(String password, InputStream keystoreTrustStream) throws CertificateException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException, IOException {
        return createSSLContext(null,password,keystoreTrustStream);
    }

}
